package com.king.student.dao;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import com.king.student.entity.Course;
import com.king.student.sql.SqlUtility;

public class CourseDao {

	//添加一门课程
	public static boolean addCourse(Course course){
		try {
			String sql = "insert into course values(?,?,?)";
			PreparedStatement ps = SqlUtility.getConnection().prepareStatement(sql);
			ps.setString(1, course.getCourseID());
			ps.setString(2, course.getCourseName());
			ps.setString(3, course.getCourseTeacher());
			ps.execute();
			return true;
		} catch (SQLException e) {
		}
		return false;
	}
	
	//删除一门课程
	public static boolean delCourse(String courseID){
		try {
			String sql = "delete from course where courseID=?";
			PreparedStatement ps = SqlUtility.getConnection().prepareStatement(sql);
			ps.setString(1, courseID);
			ps.execute();
			return true;
		} catch (SQLException e) {
		}
		return false;
	}
	
	//更新课程信息
	public static boolean updateCourse(Course course){
		try {
			String sql = "update course set courseName=?,courseTeacher=? where courseID=?";
			PreparedStatement ps = SqlUtility.getConnection().prepareStatement(sql);
			ps.setString(1, course.getCourseName());
			ps.setString(2, course.getCourseTeacher());
			ps.setString(3, course.getCourseID());
			ps.execute();
			return true;
		} catch (SQLException e) {
		}
		return false;
	}
	
	//查询所有课程
	public static List<Course> getCourseAll(){
		try {
			String sql = "select * from course";
			PreparedStatement ps = SqlUtility.getConnection().prepareStatement(sql);
			ResultSet rs = ps.executeQuery();
			List<Course> list = new ArrayList<>();
			
			while(rs.next()){
				Course course = new Course();
				course.setCourseID(rs.getString("courseID"));
				course.setCourseName(rs.getString("courseName"));
				course.setCourseTeacher(rs.getString("courseTeacher"));
				list.add(course);
			}
			return list;
		} catch (SQLException e) {
		}
		return Collections.emptyList();
	}
	
	//根据课程编号获取课程信息
	public static Course getCourseByCourseID(String courseID){
		try {
			String sql = "select * from course where courseID=?";
			PreparedStatement ps = SqlUtility.getConnection().prepareStatement(sql);
			ps.setString(1, courseID);
			ResultSet rs = ps.executeQuery();
			rs.next();
			Course course = new Course();
			course.setCourseID(rs.getString("courseID"));
			course.setCourseName(rs.getString("courseName"));
			course.setCourseTeacher(rs.getString("courseTeacher"));
			return course;
		} catch (SQLException e) {
		}
		return null;
	}
	
}
